import axios from "axios";
import router from "@/router";
import {useUserStore} from '@/stores/user.ts'
import {ElMessage,ElMessageBox,ElTree,ElTable } from 'element-plus'
import { loginInfo } from "./user";

const request = axios.create({
    baseURL:'/api',
    timeout:60000,
    headers:{'Content-Type':'application/json;charset=utf-8'}
});
request.interceptors.request.use(
    (config)=>{
		const userStore = useUserStore();
        const token = userStore.token
		const expiredTime = userStore.expireTime
        if(token != undefined && token != ''){
            const now = new Date().getTime();
            //过期的话，拦截
            if(expiredTime < now){
				userStore.clearToken()
                router.push("/login")
            }else{
                if(config && config.headers){
                    config.headers.Authorization=`${token}`;
                }
            }
        }else if(config.url != '/user/login'){
            router.push("/login")
        }
        return config;
    },
    (error: any)=>{
        return Promise.reject(error);
    }
)

request.interceptors.response.use(
    (response)=>{
		const userStore = useUserStore();
        const code = response.data.code;
        if(code == 401){
			userStore.clearToken()
            router.push("/login")
        }else if(code == 200){
            // router.push("/")
        }else if(code == 403){
		   ElMessage({
		     type: 'warning',
		     message: response.data.msg,
		   })
        }else if(code == 500){
            ElMessage({
                type: 'warning',
                message: response.data.msg,
            })
        }
        return response;
    },
    (error: { response: { status: any; }; })=>{
        const code = error.response ? error.response.status:null;
        console.log("ddd:"+error)
        if(code == 403){
			ElMessage({
			  type: 'warning',
			  message: "服务端连接失败，请联系管理员查看",
			})
         }else if(code == 500){
            ElMessage({
                type: 'warning',
                message: error.response.data.message,
            })
        }
        return Promise.reject(error)
    }
)

export function get(url: string,params: null | undefined){
    if(params == undefined){
        params = null;
    }
    return new Promise((resolve,reject)=>{
        request.get(url,{params:params}).then((response: { data: unknown; })=>{
            resolve(response.data)
        }).catch((err: any)=>{
            reject(err)
        })
    })
}
export function post(url: string,data: object | undefined){
    return new Promise((resovle,reject)=>{
        request.post(url,JSON.stringify(data)).then((response: { data: unknown; })=>{
			if (response.data.code == 200){
				const userStore = useUserStore();
				if (url.includes('menu')){
					userStore.setMenus().then(()=>{
						console.log("结果2："+userStore.menues)
					})
				}else if (url.includes('dict')){
                    userStore.getDictionary().then(()=>{
                        console.log("结果3："+userStore.menues)
                    })
                }else if (url.includes('role')){
					loginInfo().then((res)=>{
						if(res.code === 200){
							userStore.setUserInfo(res.data)
						}
					})
				}
			}
            resovle(response.data);
        }).catch((err: any)=>{
            reject(err);
        })
    })
}
export function postImg(url: string,formData: object | undefined){
    const userStore = useUserStore();
    const token = userStore.token
    return new Promise((resovle,reject)=>{
        request.post(url,formData,
            {
                headers:{
                    'Content-Type':'multipart/form-data',
                    'Authorization':`${token}`
                }
            }).then((response: { data: unknown; })=>{
            resovle(response.data);
        }).catch((err: any)=>{
            reject(err);
        })
    })
}
export function put(url: string,data: any){
    return new Promise((resovle,reject)=>{
        request.put(url,JSON.stringify(data)).then((response: { data: unknown; })=>{
			if (response.data.code == 200){
				const userStore = useUserStore();
				if (url.includes('menu')){
					userStore.setMenus().then(()=>{
						console.log("结果2："+userStore.menues)
					})
				}else if (url.includes('role')){
					loginInfo().then((res)=>{
						if(res.code === 200){
							userStore.setUserInfo(res.data)
						}
					})
				}
			}
            resovle(response.data);
        }).catch((err: any)=>{
            reject(err);
        })
    })
}
export function del(url: string,params: undefined){
    return new Promise((resolve,reject)=>{
        request.delete(url,{data:params}).then((response: { data: unknown; })=>{
			if (response.data.code == 200){
				const userStore = useUserStore();
				if (url.includes('menu')){
					userStore.setMenus().then(()=>{
						console.log("结果2："+userStore.menues)
					})
				}else if (url.includes('dict')){
                    userStore.getDictionary().then(()=>{
                        console.log("结果3："+userStore.menues)
                    })
                }else if (url.includes('role')){
					loginInfo().then((res)=>{
						if(res.code === 200){
							userStore.setUserInfo(res.data)
						}
					})
				}
			}
            resolve(response.data)
        }).catch((err: any)=>{
            reject(err)
        })
    })
}
export default request;